//
//  ZMTabBar.swift
//  LoveBeen
//
//  Created by pg on 2017/8/6.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit

class ZMTabBar: UITabBar {

    var count: Int = 0{
        didSet{
            if count < 0{
                count = 0
            }
            
            if count == 0 {
                redView.isHidden = true
            }else{
                redView.isHidden = false
                
                redView.text = "\(count)"
                
                redAnimationStart()
            }
            
        }
    }
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
       
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载红色小圆点
    fileprivate lazy var redView: UILabel = {
       
        let redlabel = UILabel(text: "", fontSize: 10, textColor: UIColor.white)
        redlabel.textAlignment = .center
        redlabel.backgroundColor = UIColor.red
        redlabel.layer.cornerRadius = 8
        redlabel.layer.masksToBounds = true
       // redlabel.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
        redlabel.isHidden = true
        
        return redlabel
    }()
    
    
   //向购物车按钮添加红色小圆点
    func setupUI(){
        
        let barItem = self.subviews[2]
        let imageview = barItem.subviews.first as! UIImageView
        
        imageview.addSubview(redView)
        redView.snp.makeConstraints { (make) in
            make.top.equalTo(imageview).offset(-5)
            make.leading.equalTo(imageview.snp.trailing).offset(3)
            make.size.equalTo(CGSize(width: 16, height: 16))
        }
        
        
        //注册通知监听
        NotificationCenter.default.addObserver(self, selector: #selector(countChanged(info:)), name: NSNotification.Name(TabBatRedViewCountChangedNotification), object: nil)
        
    }
    
    func countChanged(info:Notification) -> Void {
         let array = info.object as! [ZMProductsModel]
        
        var num: Int = 0
        for model in array{
            
           num +=  model.buyNum
        }
        
        self.count = num
        
    }
    
    
    //设置动画
    func redAnimationStart(){
        
        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        animation.duration = 0.12
        animation.repeatCount = 1
        animation.autoreverses = true
        animation.fromValue = NSNumber(value: 0.5)
        animation.toValue = NSNumber(value: 1.3)
        redView.layer.add(animation, forKey: nil)
    }
    
    
    override func setItems(_ items: [UITabBarItem]?, animated: Bool) {
        
        
        super.setItems(items, animated: animated)
        
        setupUI()
    }
    
}
